//
//  AppDelegate.m
//  Go!
//
//  Created by 凌風 on 16/7/7.
//  Copyright © 2016年 凌风. All rights reserved.
//

#import "AppDelegate.h"
#import<CoreLocation/CoreLocation.h>
#import "LBFTabBarController.h"
#import "NetWorkManager.h"
#import "Tools.h"
#import "MHCHCitysModel.h"
#import <CoreLocation/CoreLocation.h> // 地图定位
#import "HQYGetLocationNetworkingManager.h" // 经纬度转地址
#import "NetWorkManager.h" // 网络请求
#import "UIImage+GIF.h" // 加载动态图片的类目

#pragma mark -- 三方登录
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>

// 腾讯开放平台SDK
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>
// 微信SDK
#import "WXApi.h"
// 新浪微博SDK
#import "WeiboSDK.h"
//新浪微博SDK需要在项目Build Settings中的Other Linker Flags添加"-ObjC"
#pragma mark -- 短信验证
#import <SMS_SDK/SMSSDK.h>

@interface AppDelegate ()<CLLocationManagerDelegate>
{
    CLLocationManager *_locationManager; /**< 定位服务 */
    UIView *_loadView; /**< 加载等待视图 */
}

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [self initializeDataSource];
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    LBFTabBarController *tabBarVc = [[LBFTabBarController alloc] init];
    
    CATransition *anim = [[CATransition alloc] init];
    anim.type = @"rippleEffect";
    anim.duration = 1.0;
    
    [self.window.layer addAnimation:anim forKey:nil];
    
    self.window.rootViewController = tabBarVc;
    
    tabBarVc.selectedIndex = 2;
    
    [self.window makeKeyAndVisible];
    
    CLLocationManager* location = [CLLocationManager new];
    [location requestAlwaysAuthorization];
    
    // 加载等待视图
    [UIView animateWithDuration:2.0 animations:^{
        [self loadingImageMethod];
    } completion:^(BOOL finished) {
        /**< 移除等待视图 */
        [_loadView removeFromSuperview];
        _loadView = nil;
    }];
    
    // 三方登录
    [ShareSDK registerApp:@"Go" activePlatforms:@[@(SSDKPlatformTypeSinaWeibo)] onImport:^(SSDKPlatformType platformType) {
        switch (platformType) {
            case SSDKPlatformTypeSinaWeibo:
                [ShareSDKConnector connectWeibo:[WeiboSDK class]];
                break;
                
            default:
                break;
        }
    } onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo) {
        switch (platformType) {
            case SSDKPlatformTypeSinaWeibo:
                [appInfo SSDKSetupSinaWeiboByAppKey:@"4114232224"
                                          appSecret:@"806f8c5fb229c7b809abdff80594613e"
                                        redirectUri:@"http://www.sharesdk.cn"
                                           authType:SSDKAuthTypeBoth];
                break;
                
            default:
                break;
        }
    }];
    
    // 短信验证码
    [SMSSDK registerApp:@"15234db311eb6" withSecret:@"fc33b8fd75628fec3fdc2ce081e771b8"];
    
    return YES;
}

// 加载等待gif图片，当定位成功之后才取消
- (void)loadingImageMethod {
    // 等待的视图
    _loadView = [[UIView alloc] initWithFrame:self.window.frame];
    _loadView.backgroundColor = ColorWith(249, 190, 53);
    
    // gif动态图片
    UIImageView *gifImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.window.center.y * 0.4, ScreenW, Size_H(311))];
    gifImage.image = [UIImage windy_animatedGIFNamed:@"loading"];
    
    // 文字
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(gifImage.frame), ScreenW, 40)];
    label.text = @"正在加载，请耐心等待....";
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:Font(24)];
    
    // 文字
    UILabel *teamLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(label.frame), ScreenW, 30)];
    teamLabel.text = @"开发团队：穆华春、林波、黄秋燕";
    teamLabel.font = [UIFont systemFontOfSize:Font(18)];
    teamLabel.textAlignment = NSTextAlignmentCenter;
    teamLabel.textColor = [UIColor whiteColor];
    
    
    [_loadView addSubview:gifImage];
    [_loadView addSubview:label];
    [_loadView addSubview:teamLabel];
    [self.window addSubview:_loadView];
}

- (void)initializeDataSource {
    [[NSUserDefaults standardUserDefaults] setObject:@"800010000" forKey:currentCity_ID];
    [[NSUserDefaults standardUserDefaults] setObject:@"成都" forKey:currentCity_Name];
    
    if (![CLLocationManager locationServicesEnabled]) { // 不支持定位
        // 弹框提示用户：设备不支持定位
        [Tools showAlertWithMessage:@"您的设备暂未开启定位服务!"];
        return;
    }
    // 初始化定位服务
    _locationManager = [[CLLocationManager alloc] init];
    // 请求用户授权
    [_locationManager requestAlwaysAuthorization];
    [_locationManager requestWhenInUseAuthorization];
    // 获取定位的状态（成功/失败）
    _locationManager.delegate = self;
    [_locationManager startUpdatingLocation];
}


#pragma mark - 定位
#pragma mark --定位失败
- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error {
    [Tools showAlertWithMessage:@"定位失败"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"sendCurrentCityName" object:@"成都"];
}

#pragma mark --定位成功
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    // 获取最新的定位信息
    CLLocation *location = locations.lastObject;
    
    // 停止定位
    [_locationManager stopUpdatingLocation];
    
    // 保存当前手机经纬度坐标
    NSDictionary *locationDic = @{@"lon":@(location.coordinate.longitude), @"lat":@(location.coordinate.latitude)};
    [[NSUserDefaults standardUserDefaults] setObject:locationDic forKey:currentCity_Location];
    
    // 根据经纬度获得城市
    [HQYGetLocationNetworkingManager postWithParams:@{@"lng":[NSString stringWithFormat:@"%f", location.coordinate.longitude], @"lat":[NSString stringWithFormat:@"%f", location.coordinate.latitude], @"from":@"5"} Successblock:^(id responseObject) {
        // 获得当前定位城市
        NSString *city = responseObject[@"showapi_res_body"][@"addressComponent"][@"city"];
        [NetWorkManager getWithURL:@"cities" urlParam:nil successBlock:^(id responseObject) {
            // 获得所有的城市
            NSArray *citiesArray = [responseObject objectForKey:@"cities"];
            [[NSUserDefaults standardUserDefaults] setObject:citiesArray forKey:AllCitiesArray];
            
            // 查找是否有当前城市
            for (NSDictionary *obj in citiesArray) {
                if ([obj[@"city_name"] isEqualToString:city]) {
                    // 保存当前的城市ID
                    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%@", obj[@"city_id"]] forKey:currentCity_ID];
                    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%@", obj[@"short_name"]] forKey:currentCity_Name];
                    /**< 通知传值，传递当前城市的名字，同时可取消首页的等待加载中的视图 */
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"sendCurrentCityName" object:obj[@"short_name"]];
                    [Tools showAlertWithMessage:@"定位成功"];
                }
            }
            [[NSUserDefaults standardUserDefaults] synchronize];
            [MHCHCitysModel getTheCitys];
            
        } FailureBlock:nil];
        
    } Failblock:nil]; 
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
